package com.orangelife.mobile.surrounding.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.common.jump.WebJumper;
import com.common.util.OrangePhoneUtil;
import com.curry.android.http.HttpUtil;
import com.curry.android.util.DialogHelper;
import com.curry.android.util.ImageDownloader;
import com.curry.android.util.IntentHelper;
import com.curry.android.util.JSONHelper;
import com.curry.orangelife.mobile.R;
import com.orangelife.mobile.activities.adapter.ActivityDetailListViewAdapter;
import com.orangelife.mobile.activities.biz.InnerListView;
import com.orangelife.mobile.app.application.ExitApplication;
import com.orangelife.mobile.common.activity.OrangeLifeBaseActivity;
import com.orangelife.mobile.common.biz.JSONRequest;
import com.orangelife.mobile.constants.Constant;
import com.orangelife.mobile.individual.activity.MyOrderDetailActivity;
import com.orangelife.mobile.shoppingcart.activity.ShoppingCartActivity;
import com.orangelife.mobile.shoppingcart.biz.ShoppingCartBiz;
import com.thirdsdk.umeng.UmShareBiz;
import com.orangelife.mobile.util.BLog;
import com.orangelife.mobile.util.StringUtil;
import com.orangelife.mobile.util.ToastHelper;
import com.orangelife.mobile.widget.MyScrollview;
import com.orangelife.mobile.web.WebWin;
import com.umeng.socialize.media.UMImage;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by yyx
 * on 2015/10/9.
 */
public class HotGoodsDetailActivity extends OrangeLifeBaseActivity {

    @Bind(R.id.tv_title)
    TextView tvTitle;
    @Bind(R.id.iv_title_call)
    ImageView ivTitleCall;
    @Bind(R.id.iv_title_shopping_cart)
    ImageView ivShoppingCart;
    @Bind(R.id.tvGoodNumber)
    TextView tvGoodNumber;
    @Bind(R.id.flShoppingCart)
    FrameLayout flShoppingCart;
    @Bind(R.id.ivBigPhoto)
    ImageView ivBigPhoto;
    @Bind(R.id.tvGoodsName)
    TextView tvGoodsName;
    @Bind(R.id.ibShare)
    ImageButton ibShare;
    @Bind(R.id.tvSelectStandard)
    TextView tvSelectStandard;
    @Bind(R.id.tvCommercialTnantName)
    TextView tvCommercialTnantName;
    @Bind(R.id.tvGoodsDetail)
    TextView tvGoodsDetail;
    @Bind(R.id.wwPhoto)
    WebWin wwPhoto;
    @Bind(R.id.tvBuyPriceDiscount)
    TextView tvBuyPriceDiscount;
    @Bind(R.id.tvBuyPrice)
    TextView tvBuyPrice;
    @Bind(R.id.tvAddShoppingCart)
    TextView tvAddShoppingCart;
    @Bind(R.id.tvBuy)
    TextView tvBuy;
    @Bind(R.id.tvGoodsZeng)
    TextView tvGoodsZeng;  //积分比例
    @Bind(R.id.tvJifenTip)
    TextView tvJifenTip; //赠送积分
    @Bind(R.id.zeng)
    TextView zeng; //赠送积分

    @Bind(R.id.lvConsumerTips)
    InnerListView lvConsumerTips;
    @Bind(R.id.slSlide)
    MyScrollview slSlide;
    @Bind(R.id.llTitle)
    LinearLayout llTitle;
    @Bind(R.id.ib_back)
    ImageButton ibBack;
    @Bind(R.id.tv1)
    TextView tv1;

    private float alpha=0.0f;
    /**
     * list传过来的数据
     */
    private Map<String, Object> map;

    /**
     * 服务端接收过来的数据
     */
    private Map<String, Object> mapDetail;
    /**
     * 分享图片
     */
    @SuppressWarnings("unused")
    private UMImage umengImage;
    /**
     * 分享title
     */
    private String uMtitle = "";
    /**
     * 分享content
     */
    private String uMcontent = "";

    private List<Map<String, Object>> listSummary = null;

    private List<Map<String, Object>> listProduct = null;

    /**
     * 图片下载
     */
    private ImageDownloader image = ImageDownloader.getImageDownloader();
    private String merId;

    private String goodsID = "";
    UmShareBiz shareBiz;
    private static final int REQUEST_SELECT_STANDARD=888;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_circumtesco_hotgoods_detail2);
        ButterKnife.bind(this);
        tv1.setText(Constant.RMB_FLAG);
        shareBiz = new UmShareBiz(this);
        findView();
        setScroll();
    }

    private int[] drawables={};
    private void setScroll() {
        llTitle.getBackground().setAlpha(0);
        slSlide.setScrollListener(new MyScrollview.ScrollViewListener() {
            @Override
            public void scorlling(int scrollY, int oldScrollY) {
                int alphaNow=255;
                alphaNow= (int) (scrollY<200?alphaNow*(scrollY/200.0f):255);
                llTitle.getBackground().setAlpha(alphaNow);
                if (alphaNow > 200) {
                    ibBack.setBackgroundResource(R.drawable.back_orange);
                    ivTitleCall.setBackgroundResource(R.drawable.icon_phone);
                    ivShoppingCart.setBackgroundResource(R.drawable.icon_shoppingcar);
                }else{
                    ibBack.setBackgroundResource(R.drawable.ic_shadow_back);
                    ivTitleCall.setBackgroundResource(R.drawable.ic_shadow_phone);
                    ivShoppingCart.setBackgroundResource(R.drawable.ic_shadow_cart);
                }

            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (getGoodsNumber() == 0) {
            tvGoodNumber.setVisibility(View.GONE);
        } else {
            tvGoodNumber.setVisibility(View.VISIBLE);
            tvGoodNumber.setText(getGoodsNumber() + "");
        }

        BLog.getInstance().inMerDetail(id);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        BLog.getInstance().outMerDetail(id);
    }

    /***
     * 赋值
     */
    private void findView() {
        ExitApplication.getInstance().addPaidActivity(this);
        Intent intent = getIntent();
        goodsID = intent.getStringExtra("goodsID");
        tvTitle.setText(R.string.trade_detail);
        ivTitleCall.setOnClickListener(listener);
        flShoppingCart.setOnClickListener(listener);
        tvSelectStandard.setOnClickListener(listener);
        tvBuy.setOnClickListener(listener);
        tvAddShoppingCart.setOnClickListener(listener);
        tvJifenTip.setOnClickListener(listener);
        ibShare.setOnClickListener(listener);
        map = (Map<String, Object>) intent.getSerializableExtra("detail");
        getDataFromServer();
        getActivityDetail();
//        ToastHelper.getInstance().init(this);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        goodsID = intent.getStringExtra("goodsID");
        map = null;
        getDataFromServer();
        getActivityDetail();

    }

    private int getGoodsNumber() {
        return ShoppingCartBiz.getGoodsCount();
    }

    /**
     * 下拉刷新的进度条
     */
    private void getDataFromServer() {
        dialog = DialogHelper.getInstance().createLoadingDialog(this,
                Constant.LOADING);
        dialog.show();
    }

    /**
     * 行为采集使用ID
     */
    String id = null;

    /**
     * 获得详情
     */
    @SuppressWarnings("deprecation")
    private void getActivityDetail() {
        Map<String, Object> mapSubmit = new HashMap<String, Object>();
        Intent intent = getIntent();
//        mapSubmit.put("commID", SharePreferenceUtilNew.getInstance().getComInfo().get("commID"));
        if (map != null && map.size() != 0) {
            id = map.get("goodsID").toString();
            mapSubmit.put("{goodsID}", map.get("goodsID").toString());
        } else if (!StringUtil.isBlank(intent.getStringExtra("id"))) {
            id = intent.getStringExtra("id");
            mapSubmit.put("{goodsID}", intent.getStringExtra("id"));
        } else {
            mapSubmit.put("{goodsID}", goodsID);
            id = goodsID;
        }
        Map<String, Object> rootMap = new HashMap<>();
        rootMap.put("map", mapSubmit);
        rootMap.put("url", Constant.URL_HOTGOODS_DETAIL_NEW);
        rootMap.put("wat", 6);
        new JSONRequest(JSONRequest.GET, rootMap, handler, HttpUtil.ACTION_URI);
    }

    private View.OnClickListener listener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.tvJifenTip:
                    WebJumper.jumpToJifenGongFang(HotGoodsDetailActivity.this);
                    break;
                case R.id.iv_title_call:
                    /*打电话*/
                    OrangePhoneUtil.callCustomerService2(HotGoodsDetailActivity.this);
                    break;
                case R.id.flShoppingCart:
                    /*跳转购物车页面*/
                    IntentHelper.getInstances().getIntent(HotGoodsDetailActivity.this, ShoppingCartActivity.class);
                    break;
                case R.id.ibShare:
                    shareBiz.share(uMtitle,uMcontent,Constant.HOTGOODS_SHARE_URL,merId);
                    break;
                case R.id.tvSelectStandard:
                    if (mapDetail != null) {
                        ExitApplication.getInstance().addFailActivity(HotGoodsDetailActivity.this);
                        Intent intent = new Intent();
                        Bundle bundle = new Bundle();
                        intent.putExtra("position", position);
                        intent.putExtra("flag", 1);
                        bundle.putSerializable("specification",
                                (Serializable) mapDetail);
                        intent.putExtras(bundle);
                        intent.setClass(HotGoodsDetailActivity.this,
                                SelectedStandardActivity.class);
                        startActivityForResult(intent,REQUEST_SELECT_STANDARD);
                    }
                    break;
                case R.id.tvAddShoppingCart:
                    if (mapDetail != null) {
                        ExitApplication.getInstance().addFailActivity(HotGoodsDetailActivity.this);
                        Intent intent = new Intent();
                        Bundle bundle = new Bundle();
                        intent.putExtra("position", position);
                        intent.putExtra("flag", 2);
                        bundle.putSerializable("specification",
                                (Serializable) mapDetail);
                        intent.putExtras(bundle);
                        intent.setClass(HotGoodsDetailActivity.this,
                                SelectedStandardActivity.class);
                        startActivityForResult(intent,REQUEST_SELECT_STANDARD);
                    }
                    break;
                case R.id.tvBuy:
                    if (mapDetail != null) {
                        ExitApplication.getInstance().addFailActivity(HotGoodsDetailActivity.this);
                        Intent intent = new Intent();
                        Bundle bundle = new Bundle();
                        intent.putExtra("position", position);
                        intent.putExtra("flag", 3);
                        bundle.putSerializable("specification",
                                (Serializable) mapDetail);
                        intent.putExtras(bundle);
                        intent.setClass(HotGoodsDetailActivity.this,
                                SelectedStandardActivity.class);
                        startActivityForResult(intent,REQUEST_SELECT_STANDARD);
                    }
                    break;
                default:
                    break;
            }

        }
    };

    private int position;
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_SELECT_STANDARD && resultCode == RESULT_OK) {
            if (data != null) {
                position= data.getIntExtra("position",0);
                setProduct(listProduct.get(position));
            }
        }
    }

    /**
     * 处理返回的信息数据
     */
    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        @SuppressWarnings("unchecked")
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 15:
                    String errInfo = JSONHelper.jsonToMap(msg.obj.toString())
                            .get("errInfo").toString();
                    String orderID = JSONHelper.jsonToMap(msg.obj.toString())
                            .get("orderID").toString();
                    if (errInfo.equals("OK")) {
                        DialogHelper.closeDialog(dialog);
                        finish();
                        ToastHelper.getInstance()._toast(
                                getResources().getString(R.string.submit_success));
//                        if(type == 2){
//                            return;
//                        }
                        Intent intent = new Intent();
                        Bundle bundle = new Bundle();
                        Map<String, Object> mapOrder = new HashMap<String, Object>();
                        mapOrder.put("orderID", orderID);
//                        mapOrder.put("orderType", type);
                        bundle.putSerializable("map", (Serializable) mapOrder);
                        intent.setClass(HotGoodsDetailActivity.this,
                                MyOrderDetailActivity.class);
                        intent.putExtras(bundle);
                        startActivity(intent);
                    } else {
                        DialogHelper.closeDialog(dialog);
                        ToastHelper.getInstance()._toast(
                                getResources().getString(
                                        R.string.complaintes_sumbite_fail));
                    }
                    break;
                case 6:
                    DialogHelper.closeDialog(dialog);
                    mapDetail = new HashMap<>();
                    mapDetail = (Map<String, Object>) JSONHelper.jsonToMap(
                            msg.obj.toString()).get("entity");
                    setDetail();
                    break;
                case 500:
                    DialogHelper.closeDialog(dialog);
                    ToastHelper.getInstance()._toast(msg.obj.toString());
                    break;
                case 1011:
                    isLogin(dialog, HotGoodsDetailActivity.this);
                    break;
                case 15001:
                    ToastHelper.getInstance()._toast(
                            getResources().getString(R.string.goods_undercarriage));
                    tvBuy.setEnabled(false);
                    break;
                default:
                    break;
            }
        }

    };

    /***
     * 设置详情
     */
    private void setDetail() {
        WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        int width = wm.getDefaultDisplay().getWidth();
        int height = width * 11 / 16;
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(width, width);
        ivBigPhoto.setLayoutParams(params);
        merId = String.valueOf(mapDetail.get("goodsID"));
        uMtitle = String.valueOf(mapDetail.get("goodsName"));
        uMcontent = String.valueOf(mapDetail.get("goodsBrief"));
        image.download(String.valueOf(mapDetail.get("goodsLogo")).trim(), ivBigPhoto,
                ImageDownloader.ImageSize.IMAGE_SIZE_MIDDLE_JPG);
        tvGoodsName.setText(String.valueOf(mapDetail.get("goodsName")));
        tvCommercialTnantName.setText(String.valueOf(mapDetail.get("merchantName")));
        String summary = String.valueOf(mapDetail.get("summary"));
        if (!StringUtil.isBlank(summary)) {
            listSummary = (List<Map<String, Object>>) mapDetail.get("summary");
            ActivityDetailListViewAdapter adapter = new ActivityDetailListViewAdapter(
                    this, listSummary);
            lvConsumerTips.setAdapter(adapter);
        }
        tvGoodsDetail.setText(String.valueOf(mapDetail.get("goodsDesc")));
        listProduct = (List<Map<String, Object>>) mapDetail.get("products");
        if (listProduct != null && listProduct.size()>0) {
            setProduct(listProduct.get(0));
        }else{
            tvJifenTip.setVisibility(View.GONE);
            zeng.setVisibility(View.GONE);
        }
        setWebView();
    }

    private void setProduct(Map<String,Object> product){
        tvBuyPriceDiscount.setText(String.valueOf(product.get("price")));
        tvBuyPrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
        tvBuyPrice.setText("¥" + String.valueOf(product.get("mkPrice")));
        String points = String.valueOf(product.get("points"));//'赠送积分'
        String deduction = String.valueOf(product.get("deduction"));//--'可抵扣百分比'
        String pdtDesc = String.valueOf(product.get("pdtDesc"));//规格
        zeng.setVisibility(View.VISIBLE);
        tvGoodsZeng.setText("橙汁最高抵扣"+deduction+"%");
        tvJifenTip.setText(points+"ml橙汁");
        tvSelectStandard.setText(pdtDesc);
    }

    /**
     * 设置照片的webview
     */
    private void setWebView() {
        String pics = String.valueOf(mapDetail.get("goodsImgs"));
        wwPhoto.loadDataWithBaseURL(pics);
    }


}

